package cn.iocoder.yudao.module.dr.service.sourcecatalog;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.dr.controller.admin.sourcecatalog.vo.SourceCatalogPageReqVO;
import cn.iocoder.yudao.module.dr.controller.admin.sourcecatalog.vo.SourceCatalogSaveReqVO;
import cn.iocoder.yudao.module.dr.dal.dataobject.sourcecatalog.SourceCatalogDO;
import cn.iocoder.yudao.module.dr.dal.mysql.sourcecatalog.SourceCatalogMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.dr.enums.ErrorCodeConstants.SOURCE_CATALOG_NOT_EXISTS;

/**
 * 资源编目 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SourceCatalogServiceImpl implements SourceCatalogService {

    @Resource
    private SourceCatalogMapper sourceCatalogMapper;

    @Override
    public Long createSourceCatalog(SourceCatalogSaveReqVO createReqVO) {
        // 插入
        SourceCatalogDO sourceCatalog = BeanUtils.toBean(createReqVO, SourceCatalogDO.class);
        sourceCatalogMapper.insert(sourceCatalog);
        // 返回
        return sourceCatalog.getId();
    }

    @Override
    public void updateSourceCatalog(SourceCatalogSaveReqVO updateReqVO) {
        // 校验存在
        validateSourceCatalogExists(updateReqVO.getId());
        // 更新
        SourceCatalogDO updateObj = BeanUtils.toBean(updateReqVO, SourceCatalogDO.class);
        sourceCatalogMapper.updateById(updateObj);
    }

    @Override
    public void deleteSourceCatalog(Long id) {
        // 校验存在
        validateSourceCatalogExists(id);
        // 删除
        sourceCatalogMapper.deleteById(id);
    }

    private void validateSourceCatalogExists(Long id) {
        if (sourceCatalogMapper.selectById(id) == null) {
            throw exception(SOURCE_CATALOG_NOT_EXISTS);
        }
    }

    @Override
    public SourceCatalogDO getSourceCatalog(Long id) {
        return sourceCatalogMapper.selectById(id);
    }

    @Override
    public PageResult<SourceCatalogDO> getSourceCatalogPage(SourceCatalogPageReqVO pageReqVO) {
        return sourceCatalogMapper.selectPage(pageReqVO);
    }

}